<template>
  <el-dialog
    title="新建礼物"
    :visible.sync="dialogData.isShow"
    width="480px"
    :before-close="handleBeforeClose"
  >
    <div class="form-box">
      <el-form
        ref="ruleForm"
        :rules="rules"
        :model="ruleForm"
        label-width="120px"
        class="addForm"
      >
        <el-form-item label="礼物名称:" prop="goodName">
          <el-input
            v-model="ruleForm.name"
            type="text"
            :placeholder="`请输入礼物名称(最多输入${maxLength}个字符)`"
            :maxlength="maxLength"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传礼物主图" prop="goodImg">
          <uploadSingImg
            class="upload-img__body"
            :imgUrl="ruleForm.icon"
            accept=".jpg,.jpeg,.png,.gif"
            :maxSize="0.3"
            @getImgUrl="getGoodImg"
            :disabled="isCheck"
          >
            <template v-slot:imgInfo>（限制上传300KB以内）</template>
          </uploadSingImg>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表单部分 -->
    <span slot="footer" class="dialog-footer">
      <el-button type="success" plain @click="cancel">取 消</el-button>
      <el-button type="success" :loading="loading" @click="confirm('ruleForm')"
        >确认</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件

export default {
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      isCheck: false, //是否查看
      title: '新建礼物',
      // 表单数据
      ruleForm: { ...this.dialogData.formData },
      maxLength: 5, //标题最大长度
      rules: {
        name: [
          { required: true, message: '礼物名称不能为空', trigger: 'blur' },
          { max: 5, message: '长度最大5个字符', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '礼物主图不能为空', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    uploadSingImg
  },
  mounted() {
    if (this.dialogData.type === 'edit') {
      this.title = '编辑礼物'
    }
  },
  methods: {
    getGoodImg(url) {
      this.ruleForm.icon = url
    },
    handleBeforeClose(done) {
      this.cancel()
      done()
    },
    cancel() {
      this.dialogData.isShow = false
    },
    /* 确认提交 */
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!this.ruleForm.name.trim()) {
          this.$message({
            message: '请填写礼物名称',
            type: 'warning'
          })
          return false
        }
        if (!this.ruleForm.icon) {
          this.$message({
            message: '请上传礼物素材',
            type: 'warning'
          })
          return false
        }
        if (valid) {
          this.$emit('refresh', this.ruleForm)
          this.dialogData.isShow = false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.addForm {
  padding-bottom: 10px;
}
.upload-img__body {
  margin-top: 10px;
}
</style>
